package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.util.LocalAttrUtils;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.zsmart.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class RequireFinishTimeAttrHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Override
    public void init(CommonAttrVO commonAttr) {

    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        if (KiteStringUtils.isNotEmpty(value) && value.length() == 10){
            value += " 23:59:59";
        }
        String businessType = querySceneInstService.getExtParameterValue(sceneInstId, "businessType");
        if (KiteStringUtils.isNotEmpty(businessType)) {
            KiteAttr allCommAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.WHOLE_PROCESS_TIME);
            // 修改A端完成时间的值
            if (LocalKeyConsts.REPLACE_A.equals(fieldName)||LocalKeyConsts.MV_REPLACE_A.equals(fieldName)) {
                if (Objects.nonNull(allCommAttr)) {
                    if (DateFormatUtils.compareDate(value, allCommAttr.getValue(), LocalAttrUtils.FormatByValue(value)) > 0) {
                        ErrorConsts.BUSI_COMMON_ERROR.throwOut("A端要求完成时间不能晚于全程要求完成时间");
                    }
                }
                KiteAttr aCommAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.REPLACE_A);
                if (Objects.nonNull(aCommAttr)) {
                    aCommAttr.setValue(value);
                    aCommAttr.setValueDesc(valueDesc);
                    this.checkTime(businessType, aCommAttr);
                }
            }
            // 修改Z端完成时间的值
            if (LocalKeyConsts.REPLACE_Z.equals(fieldName)||LocalKeyConsts.MV_REPLACE_Z.equals(fieldName)) {
                if (Objects.nonNull(allCommAttr)) {
                    if (DateFormatUtils.compareDate(value, allCommAttr.getValue(), LocalAttrUtils.FormatByValue(value)) > 0) {
                        ErrorConsts.BUSI_COMMON_ERROR.throwOut("Z端要求完成时间不能晚于全程要求完成时间");
                    }
                }
                KiteAttr bCommAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.REPLACE_Z);
                if (Objects.nonNull(bCommAttr)) {
                    bCommAttr.setValue(value);
                    bCommAttr.setValueDesc(valueDesc);
                    this.checkTime(businessType, bCommAttr);
                }
            }
            // 修改全程完成时间的值
            if (LocalKeyConsts.WHOLE_PROCESS_TIME.equals(fieldName)) {
                allCommAttr.setValue(value);
                allCommAttr.setValueDesc(valueDesc);
                this.checkTime(businessType, allCommAttr);
                this.AZFinishTimeLinkHandle(sceneInstId, fieldName, value, businessType);
            }
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    private void setCommonAttr(KiteAttr attr) {
        SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttr(KiteWebContext.getContext().getCurrentSceneInstId(), attr);
    }

    public void checkTime(String type, KiteAttr ...attr) {
        //A、Z端要求完成时间 不能早于当前时间

        if (Objects.isNull(attr)) {
            return;
        }
        List<KiteAttr> kiteAttrList = Arrays.asList(attr);
        if (KiteListUtils.isNotEmpty(kiteAttrList)) {
            kiteAttrList.forEach(kiteAttr -> {
                String currDate = kiteAttr.getValue();
                String originDate = kiteAttr.getOriginValue();
                String format = LocalAttrUtils.FormatByValue(currDate);
                if (DateFormatUtils.compareDate(currDate, LocalDateTime.now().format(DateTimeFormatter.ofPattern(format)), format) < 0) {
                    BssException.throwOut(KeyConsts.LOG_MODULE, "", "要求完成时间不能早于当前时间");
                }

                // 如果加急，不能晚于之前的完成时间
                if ("URGENT".equals(type) && KiteStringUtils.isNotEmpty(originDate)) {
                    if (DateFormatUtils.compareDate(currDate, originDate, format) > 0) {
                        BssException.throwOut(KeyConsts.LOG_MODULE, "","加急，要求完成时间不能晚于之前的完成时间");
                    }
                }
                // 如果是延期，不能早于之前的完成时间
                if ("POSTPONE".equals(type) && KiteStringUtils.isNotEmpty(originDate)) {
                    if (DateFormatUtils.compareDate(currDate, originDate, format) < 0) {
                        BssException.throwOut(KeyConsts.LOG_MODULE, "","延期，要求完成时间不能早于之前的完成时间");
                    }
                }
                // 校验全程要求完成时间大于当前时间
                if ("ORD10012".equals(kiteAttr.getFieldName()) && (DateFormatUtils.compareDate(currDate, LocalDateTime.now().format(DateTimeFormatter.ofPattern(format)), format) < 0)) {
                    BssException.throwOut(KeyConsts.LOG_MODULE, "","全程要求完成时间不能小于当前时间");
                }
            });
        }
    }

    private void AZFinishTimeLinkHandle(String sceneInstId, String fieldName, String value, String businessType) {
        // 加急/延期才处理
        if (!KiteStringUtils.equalsAny(businessType, "URGENT", "POSTPONE")) {
            return;
        }
        if (KiteStringUtils.isEmpty(value)) {
            return;
        }
        // A端要求完成时间
        KiteAttr aFinishDate = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.REPLACE_A);
        // Z端要求完成时间
        KiteAttr zFinishDate = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.REPLACE_Z);
        if (Objects.isNull(aFinishDate) && Objects.isNull(zFinishDate)) {
            return;
        }
        // 当天
        Date onDate = DateFormatUtils.parseStrToDate(DateFormatUtils.getFormatedDate());
        // 全程要求完成时间
        Date allCompleteDate = DateFormatUtils.parseStrToDate(value);
        // A/Z端要求完成日期 = 全程要求完成日期 - 2
        Date newDate = DateFormatUtils.addDay(allCompleteDate, -2); // 日期增加天数
        // 小于当天的取当天
        if (newDate.compareTo(onDate) < 0) {
            newDate = onDate;
        }
        String newDateStr = DateFormatUtils.formatDate(newDate, DateFormatUtils.DATE_FORMAT); // Date转String
        if (Objects.nonNull(aFinishDate)) {
            aFinishDate.setValue(newDateStr);
            aFinishDate.setValueDesc(newDateStr);
            operateSceneInstService.setCommonAttr(sceneInstId, aFinishDate);
        }
        if (Objects.nonNull(zFinishDate)) {
            zFinishDate.setValue(newDateStr);
            zFinishDate.setValueDesc(newDateStr);
            operateSceneInstService.setCommonAttr(sceneInstId, zFinishDate);
        }
    }
}
